package com.gongpingjialoan.msg;

import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.car.CarBuyDetailActivity;
import com.gongpingjialoan.activity.car.CarListActivity;
import com.gongpingjialoan.activity.main.BaseScrollFragment;
import com.gongpingjialoan.adapter.PushMessageAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.car.PushMessageBean;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:帮我找车
 * @Author: chuang
 * @Since: 2016/10/18
 * @Version:
 */

public class FindCarMsgFragment extends BaseScrollFragment implements NetDataJson.OnNetDataJsonListener, PullToRefreshBase.OnRefreshListener<ListView>, PullToRefreshBase.OnLastItemVisibleListener{

    private PullToRefreshListView pullToRefreshListView;

    private ImageView nodataImageView;

    private ListView listView;

    private View footView;

    private List<PushMessageBean> mPushMessageList;

    private NetDataJson mNetDataJson;

    private NetDataJson mCancelMeetNetDataJson;

    private PushMessageAdapter mPushMessageAdapter;

    public int mPage;

    public boolean mIsLoadingMore = true;

    public boolean mHasMore;

    public boolean isRefresh;




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.push_message_fragment , container , false);
        footView = LayoutInflater.from(getActivity()).inflate(R.layout.listview_footview, null);
        nodataImageView = (ImageView) view.findViewById(R.id.no_info);
        pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.listview);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnLastItemVisibleListener(this);
        mPushMessageList = new ArrayList<>();
        mPushMessageAdapter = new PushMessageAdapter(mPushMessageList, getActivity());

        listView = pullToRefreshListView.getRefreshableView();
        listView.addFooterView(footView);
        listView.setAdapter(mPushMessageAdapter);
        listView.removeFooterView(footView);
        listView.setClipToPadding(false);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if(position < 1)return;
                PushMessageBean.Extra extra = mPushMessageList.get(position-1).extra;
                if("viplist".equals(extra.type)){
                    Intent intent = new Intent(getActivity(), CarListActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("forcejump",extra.forcejump);
                    bundle.putString("job_id",extra.job_id);
                    bundle.putString("source",extra.source);
                    bundle.putString("type",extra.type);
                    bundle.putString("date",extra.date);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }else{
                    Intent intent = new Intent(getActivity(), CarBuyDetailActivity.class);
                    intent.putExtra("forcejump",extra.forcejump);
                    intent.putExtra("job_id",extra.job_id);
                    intent.putExtra("source",extra.source);
                    intent.putExtra("from",extra.type);
                    intent.putExtra("typevalue",extra.typevalue);
                    startActivity(intent);
                }

            }
        });

        mNetDataJson = new NetDataJson(this);
        refresh();
        return view;
    }

    private void refresh() {
        mPage = 1;
        mHasMore = true;
        isRefresh = true;
        nodataImageView.setVisibility(View.GONE);
        updateData();

    }


    private void updateData() {
        mNetDataJson.cancelTask();
        mNetDataJson.addParam("page", mPage);
        mNetDataJson.addParam("device_code", GPJApplication.getInstance().getDeviceCode());
        mNetDataJson.addParam("type","help_find_car");
        mNetDataJson.setUrl(API.get_push_message);
        mNetDataJson.request("get");
    }


    @Override
    public void onLastItemVisible() {
        if (!mHasMore) {
            // Toast.makeText(this, "没有更多了", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!mIsLoadingMore && mHasMore) {
            listView.addFooterView(footView);
            listView.setSelection(listView.getBottom());
            isRefresh = false;
            mIsLoadingMore = true;
            mPage++;
            updateData();
        }
    }

    boolean isFristLoading = true;

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        if (!isFristLoading) {
            String label =
                    "更新时间:" + DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        }
        isFristLoading = false;
        refresh();
    }

    @Override
    public void onDataJsonError(String errorMessage) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        mIsLoadingMore = false;
        Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
        pullToRefreshListView.onRefreshComplete();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mNetDataJson != null) {
            mNetDataJson.cancelTask();
            mNetDataJson = null;
        }
        if (mCancelMeetNetDataJson != null) {
            mCancelMeetNetDataJson.cancelTask();
            mCancelMeetNetDataJson = null;
        }

    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        JSONArray jsonArray = null;
        if (isRefresh) {
            mPushMessageList.clear();
            refreshList();
        }

        try {
            JSONObject jsonObject = json.getJSONObject("data");
            jsonArray = jsonObject.getJSONArray("jobs");
            if (0 == jsonArray.length()) {
                mIsLoadingMore = false;
                nodataImageView.setVisibility(View.VISIBLE);
                pullToRefreshListView.onRefreshComplete();
                return;
            }


            int size = jsonArray.length();
            for (int i = 0; i < size; i++) {
                PushMessageBean pb = new PushMessageBean();
                JSONObject object = jsonArray.getJSONObject(i);
                pb.title = object.getString("title");
                pb.content = object.getString("content");
                pb.thumbnail = object.getString("thumbnail");
                PushMessageBean.Extra extra = pb.new Extra();
                JSONObject jsonObject1 = object.getJSONObject("extra");
                extra.type = jsonObject1.getString("type");
                extra.forcejump = jsonObject1.getString("forcejump");
                extra.source = jsonObject1.getString("source");
                extra.job_id = jsonObject1.getString("job_id");
                if("detail".equals(extra.type)){
                    extra.typevalue = jsonObject1.getString("typevalue");
                }else{
                    extra.date = jsonObject1.getString("date");
                }
                pb.extra = extra;
                mPushMessageList.add(pb);
            }
            int page_num = jsonObject.getInt("total_page");
            if (page_num == mPage) {
                mHasMore = false;
            }
        } catch (JSONException e) {
            mIsLoadingMore = false;
            nodataImageView.setVisibility(View.VISIBLE);
//            Toast.makeText(getActivity(), "数据异常，请稍后再试", Toast.LENGTH_SHORT).show();
            pullToRefreshListView.onRefreshComplete();
            return;
        }
        refreshList();
        pullToRefreshListView.onRefreshComplete();
        mIsLoadingMore = false;
    }

    private void refreshList() {
        mPushMessageAdapter.setData(mPushMessageList);
    }

}